// server/app/model/inbound_order_model.js
'use strict';

module.exports = app => {
  const { STRING, INTEGER, DATE, DECIMAL, BOOLEAN, TEXT } = app.Sequelize;

  const InboundOrderModel = app.model.define('inbound_order', {
    id: {
      type: INTEGER,
      primaryKey: true,
      autoIncrement: true
    },
    inboundNumber: {
      type: STRING(50),
      allowNull: false,
      unique: true,
      field: 'inbound_number',
      comment: '入库单号'
    },
    supplierId: {
      type: INTEGER,
      allowNull: false,
      field: 'supplier_id',
      comment: '供应商ID'
    },
    inboundDate: {
      type: DATE,
      allowNull: false,
      field: 'inbound_date',
      comment: '入库日期'
    },
    totalAmount: {
      type: DECIMAL(15, 2),
      allowNull: false,
      defaultValue: 0,
      field: 'total_amount',
      comment: '总金额'
    },
    hasInvoice: {
      type: BOOLEAN,
      allowNull: false,
      defaultValue: true,
      field: 'has_invoice',
      comment: '是否含票'
    },
    invoiceStatus: {
      type: STRING(20),
      allowNull: true,
      field: 'invoice_status',
      comment: '发票状态: pending(待开票), received(已收票), uploaded(已上传)'
    },
    freight: {
      type: DECIMAL(10, 2),
      allowNull: false,
      defaultValue: 0,
      field: 'freight',
      comment: '运费'
    },
    remark: {
      type: TEXT,
      allowNull: true,
      field: 'remark',
      comment: '备注'
    },
    createdAt: {
      type: DATE,
      allowNull: false,
      defaultValue: new Date(),
      field: 'created_at',
      comment: '创建时间'
    },
    updatedAt: {
      type: DATE,
      allowNull: false,
      defaultValue: new Date(),
      field: 'updated_at',
      comment: '更新时间'
    }
  }, {
    tableName: 'inbound_orders',
    timestamps: true,
    createdAt: 'createdAt',
    updatedAt: 'updatedAt'
  });

  // 关联关系
  InboundOrderModel.associate = function() {
    app.model.InboundOrderModel.belongsTo(app.model.SupplierModel, {
      as: 'supplier',
      foreignKey: 'supplier_id'
    });
    
    app.model.InboundOrderModel.hasMany(app.model.InboundOrderItemModel, {
      as: 'items',
      foreignKey: 'inbound_order_id'
    });
  };

  return InboundOrderModel;
};